package cn.com.pc.content.handler;

import cn.com.pc.aaa.AaaException;
import cn.com.pc.rbac.client.RbacException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = RbacException.class)
    public ResponseEntity<?> rbacError(HttpServletResponse response, Exception ex) {
        log.warn("--- GlobalExceptionHandler", ex);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(new MediaType(MediaType.TEXT_HTML, StandardCharsets.UTF_8));
        return ResponseEntity.status(HttpStatus.FORBIDDEN).headers(headers).body(ex.getMessage());
    }

    @ExceptionHandler(value = AaaException.class)
    public ResponseEntity<?> aaaError(HttpServletResponse response, Exception ex) {
        log.warn("--- GlobalExceptionHandler", ex);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(new MediaType(MediaType.TEXT_HTML, StandardCharsets.UTF_8));
        return ResponseEntity.status(HttpStatus.FORBIDDEN).headers(headers).body(ex.getMessage());
    }
}
